<script setup>
	import {ref} from 'vue'
	import {
		User,
		EditPen,
		Picture,
		Menu,
		SwitchButton,
		CaretBottom,
		HomeFilled,
		
	} from '@element-plus/icons-vue'
	import avatar from '@/assets/default.png'
	import {userApi} from "@/api/user.js";
	
	//条目被点击后,调用的函数
	import {useRouter} from 'vue-router'
	
	const router = useRouter();
	import {useUserInfoStore} from '@/store/userInfo.js'
	
	const userInfoStore = useUserInfoStore();
	const getUserInfo = () => {
		userApi.userInfo().then(result => {
			//数据存储在pinia中
			userInfoStore.setUserInfo(result.data)
		})
	}
	
	getUserInfo()
	
	const userLogin = ref({})
	// Object.assign(userLogin.value,userInfoStore.user)
	userLogin.value = userInfoStore.user
	const loginUser = userInfoStore.user.role
	
	import {useTokenStore} from '@/store/token.js'
	import {addressApi} from "@/api/address.js";
	import {ElMessage} from "element-plus";
	import {noticeApi} from "@/api/notice.js";
	import LeftMenu from "@/components/LeftMenu.vue";
	
	const tokenStore = useTokenStore();
	//头像下拉框操作
	const handleCommand = (command) => {
		//判断指令
		if (command === 'logout') {
			//退出登录
			tokenStore.removeToken();
			userInfoStore.removeUserInfo();
			
			// 跳转到登录
			router.push('/login')
		} else if (command === 'updateUserInfo') {
			dialogUpdateAdminVisible.value = true
			Object.assign(user.value, userInfoStore.user)
			selectByPId(userInfoStore.user.provinceId)
			selectByCId(userInfoStore.user.cityId)
		} else if (command === 'resetPassword') {
			dialogResetPasswordVisible.value = true
			user.value = {}
		} else {
			//路由
			router.push('/user/' + command)
		}
	}
	
	//修改个人信息
	const dialogUpdateAdminVisible = ref(false)
	const user = ref({})
	// 头像
	const headers = ref({
		//携带token传递到后端
		Authorization: tokenStore.token
	});
	const handleAvatarSuccess = (result) => {
		user.value.image = result.data
	}
	
	const updateUserInfo = () => {
		userApi.update(user.value).then(result => {
			if (result.code === 0) {
				ElMessage({message: result.msg, type: 'success',})
				dialogUpdateAdminVisible.value = false
				getUserInfo()
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	//省份数据
	const pList = ref([])
	const cList = ref([])
	const aList = ref([])
	//获取分类数据
	const selectAllProvince = () => {
		addressApi.selectProvince().then(result => {
			pList.value = result.data
		})
	}
	selectAllProvince()
	const selectByPId = (value) => {
		if (value) {
			addressApi.selectByPId(value).then(result => {
				cList.value = result.data
			})
			
		}
	}
	const selectByCId = (value) => {
		if (value) {
			addressApi.selectByCId(value).then(result => {
				aList.value = result.data
			})
		}
	}
	
	//修改密码
	const dialogResetPasswordVisible = ref(false)
	const userPassword = ref({})
	const resetFormRef = ref()
	//验证重复新密码
	const rePasswordValid = (rule, value, callback) => {
		if (value === '') {
			callback(new Error('请重复新密码！'))
		} else if (value !== userPassword.value.newPassword) {
			callback(new Error("两次密码不一致！!"))
		} else {
			callback()
		}
	}
	
	//表单正则表达式验证
	const rules = ref({
		oldPassword: [
			{required: true, message: '请输入旧密码', trigger: 'blur'},
			{min: 3, max: 16, message: '密码的长度必须为3~16位', trigger: 'blur'}
		],
		newPassword: [
			{required: true, message: '请输入新密码', trigger: 'blur'},
			{min: 3, max: 16, message: '密码长度必须为3~16位', trigger: 'blur'}
		],
		reNewPassword: [
			{required: true, message: '请重复新密码', trigger: 'blur'},
			{validator: rePasswordValid, trigger: 'blur'}
		]
	})
	
	const resetInfoPassword = (formEl) => {
		if (!formEl) return
		formEl.validate((valid) => {
			if (valid) {
				userApi.uploadPassword(userPassword.value).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
						dialogResetPasswordVisible.value = false
						//退出登录
						tokenStore.removeToken();
						userInfoStore.removeUserInfo();
						// 跳转到登录
						router.push('/login')
					} else {
						ElMessage.error(result.msg)
					}
				})
			} else {
				ElMessage.error("验证失败！无法修改")
			}
		})
	}
	
	//通知数量
	const informTotal = ref('')
	const total = () => {
		noticeApi.informTotal().then(result => {
			informTotal.value = result.data
		})
	}
	total()
</script>

<template>
	<!-- element-plus中的容器 -->
	<el-container>
		<!-- 头部区域 -->
		<el-header>
			<img style="width: 210px" src="@/assets/logo.png" alt="logo"/>&nbsp;&nbsp;
			<strong>圆梦驿站管理系统,欢迎&nbsp;{{ userInfoStore.user.name }}</strong>
			<el-dropdown placement="bottom-end" @command="handleCommand" style="float: right">
				<span class="el-dropdown__box">
                        <el-avatar :src="userInfoStore.user.image?userInfoStore.user.image:avatar"/>
					<el-icon>
						<CaretBottom/>
					</el-icon>
				</span>
				<!-- 下拉菜单 -->
				<!-- command: 条目被点击后会触发,在事件函数上可以声明一 个参数,接收条目对应的指令 -->
				<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item command="updateUserInfo" :icon="User">修改资料</el-dropdown-item>
						<el-dropdown-item command="resetPassword" :icon="EditPen">修改密码</el-dropdown-item>
						<el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
					</el-dropdown-menu>
				</template>
			</el-dropdown>
		</el-header>
		<el-container class="layout-container">
			<!-- 左侧菜单 -->
			<el-aside width="200px">
				<!-- element-plus的菜单标签 -->
				<LeftMenu></LeftMenu>
			</el-aside>
			<!-- 右侧主区域 -->
			<el-container>
				<!-- 中间区域 -->
				<el-main>
<!--					 <div style="width: 1290px; height: 570px;border: 1px solid red;">
						 <router-view></router-view>
					</div> -->
					<router-view></router-view>
				</el-main>
				<!-- 底部区域 -->
				<el-footer>后台管理 ©2024 Created by Sun</el-footer>
			</el-container>
		</el-container>
	</el-container>
	
	<el-dialog v-model="dialogUpdateAdminVisible" title="修改个人信息" width="800" :lock-scroll="false">
		<el-form :model="user">
			<el-form-item label="姓名：" :label-width="100">
				<el-input v-model="user.name" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="性别" :label-width="100">
				<el-radio-group v-model="user.gender">
					<el-radio value="男" size="large" border>男</el-radio>
					<el-radio value="女" size="large" border>女</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="生日" :label-width="100">
				<div class="block">
					<el-date-picker v-model="user.birthDate" type="date" placeholder="选择日期"
									value-format="YYYY-MM-DD" :size="size"/>
				</div>
			</el-form-item>
			<el-form-item label="地址" :label-width="100">
				<el-select v-model="user.provinceId" class="m-2"
						   clearable
						   placeholder="请选择省份"
						   @change='selectByPId'
						   ar='clearSelect' style='width:200px'>
					<el-option
						v-for="item in pList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					/>
				</el-select>
				<el-select v-model="user.cityId" class="m-2"
						   clearable
						   placeholder="请选择城市"
						   @change='selectByCId'
						   ar='clearSelect' style='width:200px'>
					<el-option
						v-for="item in cList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					/>
				</el-select>
				<el-select v-model="user.areaId" class="m-2"
						   clearable
						   placeholder="请选择区县"
						   ar='clearSelect' style='width:200px'>
					<el-option
						v-for="item in aList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					/>
				</el-select>
			</el-form-item>
			<el-form-item label="联系方式：" :label-width="100">
				<el-input v-model="user.phone" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="邮箱：" :label-width="100">
				<el-input v-model="user.email" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="QQ号：" :label-width="100">
				<el-input v-model="user.qqId" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="用户头像：" :label-width="100">
				<el-upload
					class="avatar-uploader"
					action="/api/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:headers="headers"
				>
					<img v-if="user.image" :src="user.image" class="avatar"/>
					<el-icon v-else class="avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogUpdateAdminVisible = false">取消</el-button>
				<el-button type="primary" @click="updateUserInfo">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
	
	<el-dialog v-model="dialogResetPasswordVisible" title="修改密码" width="600" :lock-scroll="false">
		<el-form
			ref="resetFormRef"
			style="max-width: 600px"
			:model="userPassword"
			status-icon
			:rules="rules"
			label-width="auto"
			class="demo-ruleForm"
		>
			<el-form-item prop="oldPassword" label="原&nbsp;&nbsp;&nbsp;密&nbsp;&nbsp;&nbsp;码：" :label-width="120">
				<el-input v-model="userPassword.oldPassword" type="password" show-password autocomplete="off"/>
			</el-form-item>
			<el-form-item prop="newPassword" label="新&nbsp;&nbsp;&nbsp;密&nbsp;&nbsp;&nbsp;码：" :label-width="120">
				<el-input v-model="userPassword.newPassword" type="password" show-password autocomplete="off"/>
			</el-form-item>
			<el-form-item prop="reNewPassword" label="重复新密码：" :label-width="120">
				<el-input v-model="userPassword.reNewPassword" type="password" show-password autocomplete="off"/>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogResetPasswordVisible = false">取消</el-button>
				<el-button type="primary" @click="resetInfoPassword(resetFormRef)">
					修改密码
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style lang="scss" scoped>
	.layout-container {
		height: 90vh;
		background-color: #F4F2FA;
		margin: 0 0 0 0;
		width: 212vh;
		font-size: 18px;
		
		
		.el-header {
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 50px;
			font-size: 20px;
			
			.el-dropdown__box {
				display: flex;
				align-items: center;
				
				.el-icon {
					color: #999;
					margin-left: 10px;
				}
				
				&:active,
				&:focus {
					outline: none;
				}
			}
		}
		
		.el-aside {
			background-color: #FCFBFF;
			font-size: 18px;
			
			
			.el-menu {
				border-right: none;
				font-size: 18px;
				
			}
		}
		
		.el-footer {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			color: #666;
			height: 30px;
		}
		
	}
	
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>